package org.example.workbench.controller;

import org.example.commons.constant.Constant;
import org.example.commons.domain.ErrorInfo;
import org.example.commons.utils.DateFormatUtils;
import org.example.commons.utils.UUIDUtils;
import org.example.settings.domain.DictionaryValue;
import org.example.settings.domain.User;
import org.example.settings.service.DictionaryValueService;
import org.example.settings.service.UserService;
import org.example.workbench.domain.Contacts;
import org.example.workbench.domain.Customer;
import org.example.workbench.domain.CustomerRemark;
import org.example.workbench.domain.Tran;
import org.example.workbench.service.ContactsService;
import org.example.workbench.service.CustomerRemarkService;
import org.example.workbench.service.CustomerService;
import org.example.workbench.service.TranService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.*;

@Controller
@RequestMapping("/customer")
public class customerController {
    @Autowired
    private UserService userService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private CustomerRemarkService customerRemarkService;
    @Autowired
    private TranService tranService;
    @Autowired
    private ContactsService contactsService;
    @Autowired
    private DictionaryValueService dictionaryValueService;

    @RequestMapping("/deleteOneContactsById")
    public @ResponseBody Object deleteOneContactsById(String contactsId){
        ErrorInfo errorInfo = new ErrorInfo();
        try {
            int i = contactsService.deleteOneContactsById(contactsId);
            if (i>0){
                errorInfo.setErrorCode(Constant.ERROR_INFO_CODE_SUCCESS);
            }else {
                errorInfo.setErrorCode(Constant.ERROR_INFO_CODE_FAIL);
                errorInfo.setErrorMessage("系统繁忙，请稍后.......");
            }
        }catch (Exception e){
            e.printStackTrace();
            errorInfo.setErrorCode(Constant.ERROR_INFO_CODE_FAIL);
            errorInfo.setErrorMessage("系统繁忙，请稍后.......");
        }
        return errorInfo;
    }
    @RequestMapping("/insertOneContactsByContacts")
    public @ResponseBody Object insertOneContactsByContacts(Contacts contacts,HttpSession session){
        User user = (User) session.getAttribute(Constant.SESSION_USER);
        String customerName = contacts.getCustomerId();
        Customer customer = customerService.getCustomerDetailByName(customerName);
        String customerId = customer.getId();
        contacts.setCustomerId(customerId);
        contacts.setId(UUIDUtils.getUUID());
        contacts.setCreateBy(user.getId());
        contacts.setCreateTime(DateFormatUtils.formatDateTime(new Date()));
        ErrorInfo errorInfo = new ErrorInfo();
        try {
            int i = contactsService.insertContactByContact(contacts);
            if (i>0){
                errorInfo.setErrorCode(Constant.ERROR_INFO_CODE_SUCCESS);
            }else {
                errorInfo.setErrorCode(Constant.ERROR_INFO_CODE_FAIL);
                errorInfo.setErrorMessage("系统繁忙，请稍后.......");
            }
        }catch (Exception e){
            e.printStackTrace();
            errorInfo.setErrorCode(Constant.ERROR_INFO_CODE_FAIL);
            errorInfo.setErrorMessage("系统繁忙，请稍后.......");
        }
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("errorInfo",errorInfo);
        hashMap.put("contacts",contacts);
        return hashMap;
    }
    @RequestMapping("/toSaveTran")
    public String toSaveJsp(HttpServletRequest request,String currentCustomerId,String currentCustomerName){
        List<User> userList = userService.findAll();
        List<DictionaryValue> stageList = dictionaryValueService.selectDicValueByType(Constant.STAGE);
        List<DictionaryValue> tranList = dictionaryValueService.selectDicValueByType(Constant.TRANSACTION_TYPE);
        List<DictionaryValue> sourceList = dictionaryValueService.selectDicValueByType(Constant.SOURCE);
        request.setAttribute("userList",userList);
        request.setAttribute("stageList",stageList);
        request.setAttribute("tranList",tranList);
        request.setAttribute("sourceList",sourceList);
        request.setAttribute("currentCustomerId",currentCustomerId);
        request.setAttribute("currentCustomerName",currentCustomerName);
        return "workbench/customer/saveTran";
    }

    @RequestMapping("/toDetail")
    public String toDetail(String id,HttpServletRequest request){
        //查询该客户的基本信息
        Customer customer = customerService.getCustomerDetailById(id);
        //查询该客户下的备注信息
        List<CustomerRemark> customerRemarkList = customerRemarkService.getAllCustomerRemarkDetailById(id);
        //查询该客户关联关系的交易信息
        List<Tran> tranList = tranService.getTranDetailByCustomerId(id);
        //查询该客户下的所有联系人的信息
        List<Contacts> contactsList = contactsService.getContactsDetailByCustomerId(id);
        //从配置文件中获取可能性
        ResourceBundle bundle = ResourceBundle.getBundle("possibility", Locale.getDefault(), new ResourceBundle.Control() {
            @Override
            public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload) throws IllegalAccessException, InstantiationException, IOException {
                // 使用 UTF-8 编码加载 properties 文件
                String bundleName = toBundleName(baseName, locale);
                String resourceName = toResourceName(bundleName, "properties");
                try (InputStream stream = loader.getResourceAsStream(resourceName)) {
                    return new PropertyResourceBundle(new InputStreamReader(stream, StandardCharsets.UTF_8));
                }
            }
        });
        for (Tran tran : tranList) {
            String possibility = bundle.getString(tran.getStage());
            tran.setPossibility(possibility);
        }
        //获取数据字典值
        List<DictionaryValue> sourceList = dictionaryValueService.selectDicValueByType(Constant.SOURCE);
        List<DictionaryValue> appellationList = dictionaryValueService.selectDicValueByType(Constant.APPELLATION);
        List<User> userList = userService.findAll();
        //发送数据
        request.setAttribute("customer",customer);
        request.setAttribute("customerRemarkList",customerRemarkList);
        request.setAttribute("tranList",tranList);
        request.setAttribute("contactsList",contactsList);
        //发送字典信息
        request.setAttribute("sourceList",sourceList);
        request.setAttribute("appellationList",appellationList);
        request.setAttribute("userList",userList);
        return "workbench/customer/detail";
    }
    @RequestMapping("/deleteCustomerByIds")
    public @ResponseBody Object deleteCustomerByIds(String[] id){
        ErrorInfo errorInfo = new ErrorInfo();
        try {
            int i = customerService.deleteCustomerByIds(id);
            if (i>0){
                errorInfo.setErrorCode(Constant.ERROR_INFO_CODE_SUCCESS);
            }else {
                errorInfo.setErrorCode(Constant.ERROR_INFO_CODE_FAIL);
                errorInfo.setErrorMessage("系统繁忙，请稍后.......");
            }
        }catch (Exception e){
            e.printStackTrace();
            errorInfo.setErrorCode(Constant.ERROR_INFO_CODE_FAIL);
            errorInfo.setErrorMessage("系统繁忙，请稍后.......");
        }
        return errorInfo;
    }
    @RequestMapping("/updateOneCustomerByMap")
    public @ResponseBody Object updateOneCustomerByMap(@RequestParam Map<String,Object> map,HttpSession session){
        User user = (User) session.getAttribute(Constant.SESSION_USER);
        map.put("editBy",user.getId());
        map.put("editTime",DateFormatUtils.formatDateTime(new Date()));
        ErrorInfo errorInfo = new ErrorInfo();
        try {
            int i = customerService.updateOneCustomerByMap(map);
            if (i>0){
                errorInfo.setErrorCode(Constant.ERROR_INFO_CODE_SUCCESS);
            }else {
                errorInfo.setErrorCode(Constant.ERROR_INFO_CODE_FAIL);
                errorInfo.setErrorMessage("系统繁忙，请稍后.......");
            }
        }catch (Exception e){
            e.printStackTrace();
            errorInfo.setErrorCode(Constant.ERROR_INFO_CODE_FAIL);
            errorInfo.setErrorMessage("系统繁忙，请稍后.......");
        }
        return errorInfo;
    }
    @RequestMapping("/getCustomerById")
    public @ResponseBody Object getCustomerById(String id){
        return customerService.getCustomerById(id);
    }
    @RequestMapping("/getAllCustomerByMap")
    public @ResponseBody Object getAllCustomerByMap(@RequestParam Map<String,Object> map){
        int currentPage = Integer.parseInt((String) map.get("currentPage"));
        int pageSize = Integer.parseInt((String) map.get("pageSize"));
        int pageNo=(currentPage-1)*pageSize;
        map.put("pageNo",pageNo);
        map.put("pageSize",pageSize);
        List<Contacts> customerList = customerService.getAllCustomerByMap(map);
        int totalCount = customerService.getCustomerTotalCountByMap(map);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("customerList",customerList);
        hashMap.put("totalCount",totalCount);
        return hashMap;
    }
    @RequestMapping("/insertOneCustomerByMap")
    public @ResponseBody Object insertOneCustomerByMap(@RequestParam Map<String,Object> map, HttpSession session){
        User user = (User) session.getAttribute(Constant.SESSION_USER);
        map.put("id", UUIDUtils.getUUID());
        map.put("createBy",user.getId());
        map.put("createTime", DateFormatUtils.formatDateTime(new Date()));
        ErrorInfo errorInfo = new ErrorInfo();
        try {
            int i = customerService.insertOneCustomerByMap(map);
            if (i>0){
                errorInfo.setErrorCode(Constant.ERROR_INFO_CODE_SUCCESS);
            }else {
                errorInfo.setErrorCode(Constant.ERROR_INFO_CODE_FAIL);
                errorInfo.setErrorMessage("系统繁忙，请稍后.......");
            }
        }catch (Exception e){
            e.printStackTrace();
            errorInfo.setErrorCode(Constant.ERROR_INFO_CODE_FAIL);
            errorInfo.setErrorMessage("系统繁忙，请稍后.......");
        }
        return errorInfo;
    }
    @RequestMapping("/index")
    public String index(HttpServletRequest request){
        List<User> userList = userService.findAll();
        request.setAttribute("userList",userList);
        return "workbench/customer/index";
    }
}
